//
//  LSoAuthViewController.swift
//  新浪微博
//
//  Created by 梁森 on 16/6/26.
//  Copyright © 2016年 梁森. All rights reserved.
//

import UIKit
import AFNetworking


class LSoAuthViewController: UIViewController {
    
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()
        
    }
    
    @objc private func cancleClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillClick(){
        let jsString = "document.getElementById('userId').value = '18501318452',document.getElementById('passwd').value = 'lsmzy579499'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    func setUpUI(){
        view.backgroundColor = UIColor.whiteColor()
        setUpNav()
    }
    
    private func setUpNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancleClick")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFillClick")
        navigationItem.title = "哈哈"
    }
    
    private lazy var webView:UIWebView = {
        let view = UIWebView()
        view.delegate = self
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")!
        let request = NSURLRequest(URL: url)
        view.loadRequest(request)
        return view
        }()
}

extension LSoAuthViewController:UIWebViewDelegate{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString
        if let u = urlString where u.hasPrefix(REDIRECT_URI){
            let q = request.URL?.query
            let code = q?.substringFromIndex("code=".endIndex)
            loadUserAccount(code!)
        }
        return true
    }
}

extension LSoAuthViewController{
    func loadUserAccount(code:String){
        LSNetWorkTools.shareTools.oAuthloadUserAccount(code, success: { (response) -> () in
            guard let res = response as? [String:AnyObject] else{
                print("不是一个字典")
                return
            }
            let lsoAuthModel = LSoAuthModel(dict: res)
            self.loadUserInfo(lsoAuthModel)
            }) { (error) -> () in
               
        }
    }
    
    func loadUserInfo(oAuthModel:LSoAuthModel){
        LSNetWorkTools.shareTools.oAuthLoadUserInfo(oAuthModel, success: { (response) -> () in
            guard let res = response as? [String:AnyObject] else {
                print("不是一个字典")
                return
            }
            oAuthModel.avatar_large = res["avatar_large"]as? String
            oAuthModel.screen_name = res["screen_name"]as? String
           LSUserAccountTools.sharedTools.saveUserAccount(oAuthModel)
           let result = LSUserAccountTools.sharedTools.userOauth
            print(result)
            }) { (error) -> () in
        }
    }
}
